# -*- coding: utf-8 -*-
# author: ting.wei
# time: 2022/12/9
import requests
from jsonpath import jsonpath
from . import url1, header2, user_id1

# from proj_spec.CLUE.mobile_po.app import App
# import base.globalvars as glo
# from base.getdata import get_header, get_user_id_from_file, get_user_credential
# from base.get_config import get_header_file


# def __init():
#     global url1, header2, user_id1
#     url1 = glo.get_value('url1')
#     header2 = get_header(get_header_file(), "header2")
#     username1, password1 = get_user_credential(App.CLUE_ROLE1)
#     user_id1 = get_user_id_from_file(username1)['user_id']


def get_company_id_by_name(company_name):
    #__init()
    search_url = url1 + '/company/retrieval'
    search_data = {"keyword": company_name, "page": 1, "size": 30,
                   "sorts": [{"sortField": "regStatus", "sortOrder": "ASC"},
                             {"sortField": "qual", "sortOrder": "ASC"}]}
    search_res = requests.post(url=search_url, headers=header2, json=search_data, verify=False)
    assert search_res.status_code == 200, '查询接口访问失败'
    company_id = jsonpath(search_res.json(), f"$.list[?(@.stdName=='{company_name}')].csfId")
    assert company_id is not False, '找不到匹配的公司'
    return company_id[0]

def retrieve_company(**kwargs):
    """调用企业检索接口：文档 http://192.168.250.111:8878/doc.html#/银行对公营销/企业列表查询/retrievalCompanyUsingPOST

    :param kwargs:
    | has_qual: 是否具有资质, 默认False
    | keyword: 关键词
    | page: 分页索引号，默认1
    | qual: 资质编号的列表
    | region_codes: 区域编号的列表
    | size: 分页大小, 默认20
    | sorts: 排序规则，默认 [{"sortField":"regStatus","sortOrder":"ASC"},{"sortField":"qual","sortOrder":"ASC"}]}

    :return:
    """

    url = url1 + "/company/retrieval"

    payload = {
        "keyword": kwargs['keyword'] if 'keyword' in kwargs else '',
        "page": kwargs['page'] if 'page' in kwargs else 1,
        "size": kwargs['size'] if 'size' in kwargs else 20,
        "hasQaul": kwargs['has_qual'] if 'has_qual' in kwargs else False,
        "qual":  kwargs['qual'] if 'qual' in kwargs else [],
        "sorts": kwargs['sorts'] if 'sorts' in kwargs else [
            {
                "sortField": "regStatus",
                "sortOrder": "ASC"
            },
            {
                "sortField": "qual",
                "sortOrder": "ASC"
            }
        ]
    }

    res = requests.post(url, headers=header2, json=payload, verify=False)
    assert res.status_code==200,"企业检索失败: %s"%res.status_code
    return res.json()


def get_company_potential_customer_state(company_name):
    """
    return: 接口返回：潜客id,潜客关注状态，company_id
    """
    company_id = get_company_id_by_name(company_name)
    state_url = url1 + '/potential/customer/state'
    state_data = {"companyIds": [company_id], "userId": user_id1}
    state_res = requests.post(url=state_url, headers=header2, json=state_data, verify=False)
    assert state_res.status_code == 200, '查询企业潜客状态，接口请求失败'
    return state_res.json()[0]


def add_potential_customer(company_name):
    state = get_company_potential_customer_state(company_name)
    if state['potentialState'] is False:
        add_url = url1 + '/potential/customer'
        add_data = {"companyName": company_name, "companyId": state['companyId'], "userId": user_id1}
        add_res = requests.post(url=add_url, headers=header2, json=add_data, verify=False)
        assert add_res.status_code == 200, f'添加潜客失败：{company_name}'


def delete_potential_customer(company_name):
    state = get_company_potential_customer_state(company_name)
    if state['potentialState'] is True:
        delete_url = url1 + f"/potential/{state['id']}/marketing"
        delete_data = {"status": 0, "id": state['id'], "userId": user_id1}
        delete_res = requests.put(url=delete_url, headers=header2, json=delete_data, verify=False)
        assert delete_res.status_code == 200, f'删除潜客失败：{company_name}'


def get_company_focus_state(company_name):
    """
    return: 非关注状态返回False，关注状态返回company_id
    """
    company_id = get_company_id_by_name(company_name)
    focused_url = url1 + '/focus/company'
    focused_data = {"companyIds": [company_id], "userId": user_id1}
    focused_res = requests.post(url=focused_url, headers=header2, json=focused_data, verify=False)
    assert focused_res.status_code == 200, '查询企业是否关注，接口请求失败'
    if not focused_res.json():
        return False
    else:
        return focused_res.json()[0]


def follow_company(company_name, bind_type=0):
    """
    调用接口关注企业
    company_name: 企业名称
    bind_type: 关注分组
    """
    focus = get_company_focus_state(company_name)
    company_id = get_company_id_by_name(company_name)
    if focus is False:
        focus_url = url1 + '/focus'
        focus_data = {"bindType": bind_type, "companyIds": [company_id], "userId": user_id1}
        focus_res = requests.post(url=focus_url, headers=header2, json=focus_data, verify=False)
        assert focus_res.status_code == 200, f'关注企业接口调用失败：{company_name}'


def unfollow_company(company_name):
    """
    调用接口，取消关注企业
    """
    focus = get_company_focus_state(company_name)
    if focus:
        focus_url = url1 + '/focus'
        focus_data = {"companyId": focus, "userId": user_id1}
        focus_res = requests.put(url=focus_url, headers=header2, json=focus_data, verify=False)
        assert focus_res.status_code == 200, f'取消关注企业接口调用失败：{company_name}'